package com.hl.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

/**
 * @author 朱炫达
 */

public class OssUtils {

    public static final String typeVideo = "video";

    public static final String typeImage = "image";

    public static final String typeAvatar = "avatar";

    // 创建OSSClient实例，线程安全
    private static final OSS ossClient = new OSSClientBuilder().build(OssPropertiesUtils.END_POINT, OssPropertiesUtils.ACCESS_KEY_ID, OssPropertiesUtils.ACCESS_KEY_SECRET);

    /**
     *
     * @param file 文件
     * @param type OssUtils.typeVideo || OssUtils.typeImage
     * @return 文件云存储地址
     */
    public static String uploadFile(MultipartFile file,String type){

        try {
            InputStream inputStream = file.getInputStream();

            String fileName = file.getOriginalFilename();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            String datePath = new DateTime().toString("yyyy/MM/dd");
            fileName = type+"/"+datePath+"/"+uuid+fileName;

            ossClient.putObject(OssPropertiesUtils.BUCKET_NAME, fileName, inputStream);

            return  "https://"+OssPropertiesUtils.BUCKET_NAME+"."+OssPropertiesUtils.END_POINT+"/"+fileName;
        } catch (Exception e) {
            System.out.println("oss error!!");
            e.printStackTrace();
        }
        return null;
    }

    /**
     *
     * @param fileUrl 文件云存储地址
     * @return boolean
     */
    public static boolean deleteFile(String fileUrl){
        try {
            String fileName = fileUrl.replace("https://"+OssPropertiesUtils.BUCKET_NAME+"."+OssPropertiesUtils.END_POINT+"/","");
            // 删除文件。
            ossClient.deleteObject(OssPropertiesUtils.BUCKET_NAME, fileName);
            return true;
        } catch (Exception e) {
            System.out.println("oss error!!");
            e.printStackTrace();
            return false;
        }
    }
}
